package com.panda.order.guanjiapo.api;


import com.alibaba.fastjson.JSONObject;
import com.panda.order.guanjiapo.Config;
import com.panda.order.guanjiapo.utils.AESCoder;
import com.panda.order.guanjiapo.utils.HttpRequest;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ApiGetToken {

    private String DoGetAuthCode() throws Exception
    {

        JSONObject pObj = new JSONObject();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        String time = dateFormat.format(now);
        pObj.put("CompanyName", Config.companyName);
        pObj.put("UserId", Config.userName);
        pObj.put("Password", Config.userpass);
        pObj.put("TimeStamp", time);

        String jsonParam = pObj.toString();
        AESCoder coder = new AESCoder();
        String p = coder.encrypt(jsonParam, Config.app_secret);

        JSONObject signObj = new JSONObject(true);

        signObj.put("appkey", Config.appkey);
        signObj.put("p", p);
        signObj.put("signkey", Config.sign_key);
        String sign = coder.SHA256(signObj.toString());


        Map<String, String> map = new HashMap<String, String>();
        map.put("appkey",Config.appkey);
        map.put("p",  URLEncoder.encode(p, "utf-8"));
        map.put("sign",sign);
        String postString = "";
        for (String in : map.keySet()) {
            postString += in + "=" +map.get(in) +"&";
        }
        postString = postString.substring(0, postString.length() - 1);
        String ret =  HttpRequest.sendPost(Config.get_authcode_url, postString);
        JSONObject jsonObject=JSONObject.parseObject(ret);
        String codeResp = jsonObject.getJSONObject("response").get("authcode").toString();
        return codeResp;
    }

    public String doGetToken()  throws Exception{
        GetTokenApi tokenObj = new GetTokenApi();
        String authCode =  DoGetAuthCode();
        String token = tokenObj.DoGetToken(authCode);
        return  token;
    }
}
